import subprocess
import git
import os
import tarfile
import random

import yaml

def format_err(errno, message = "",body = {}):
    res = {"errno": errno}
    if message != "":
        res["msg"] = message
    if body != {}:
        res["data"] = body

    return res

def is_git_dir(repo_dir) -> bool:
    command = ['git', 'rev-parse', '--is-inside-work-tree']
    process = subprocess.Popen(
        command, 
        stdout=subprocess.PIPE, 
        cwd=repo_dir,
        universal_newlines=True)
    process_output = process.communicate()[0]
    is_git = str(process_output.strip())
    return is_git == "true"

def update_repo(parent_dir, repo_name, remote, branch):
    local_path = os.path.join(parent_dir, repo_name)
    if not is_git_dir(local_path):
        git.Repo.clone_from(remote, to_path = local_path)
    repo = git.Repo(local_path)
    rem = repo.remote("origin")
    rem.fetch()
    nowbranch = repo.heads[branch]
    nowbranch.checkout()
    
def untar(fname, dirs):
    """
    解压tar.gz文件
    :param fname: 压缩文件名
    :param dirs: 解压后的存放路径
    :return: bool
    """
    try:
        t = tarfile.open(fname)
        t.extractall(path = dirs)
        return True
    except Exception as e:
        return False

def param_yaml(yaml_dir):
    if not os.path.exists(yaml_dir):
        return None

    with open(yaml_dir, 'r') as f:
        data = yaml.load(f.read(), yaml.Loader)
        return data

def generate_random_str(random_len : int):
    chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    string = ''
    for i in range(random_len):
        string += chars[random.randint(0, len(chars)-1)]
    return string